using UnityEngine;
using System.Collections;

public class Patrol : MonoBehaviour {
    public float speed = 10;
    public GameObject[] points;
    public bool orderedPatrol = true;
    private int currentTarget = 0;
    private float delta = 2f;
    private CharacterController characterController;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

	void Update () {
        if (points.Length > 0)
        {
            if (IsTargetReached())
            {
                ChooseNextTarget();
            }
            else
            {
                transform.LookAt(points[currentTarget].transform.position);
                Vector3 direction = transform.TransformDirection(Vector3.forward * speed);
                characterController.SimpleMove(direction);
            }
        }
        Debug.DrawLine(gameObject.transform.position, points[currentTarget].transform.position);
	}
	
	private void ChooseNextTarget(){
        if (orderedPatrol)
        {
            if (currentTarget < points.Length-1)
            {
                currentTarget++;
            }
            else
            {
                currentTarget = 0;
            }
        }
        else
        {
            currentTarget = Random.Range(0, points.Length);
        }
	}

    private bool IsTargetReached()
    {
        Vector3 d = gameObject.transform.position - points[currentTarget].transform.position;
        if (d.magnitude < delta)
        {
            return true;
        }
        return false;
    }
}
